//https://github.com/schteppe/p2.js/wiki/Chinese-wiki-%E4%B8%AD%E6%96%87%E7%BB%B4%E5%9F%BA#shapes%E5%BD%A2%E7%8A%B6
var  World = p2.World
	,Body = p2.Body
	,Box = p2.Box
	,Circle = p2.Circle
	,Capsule = p2.Capsule
	,Convex = p2.Convex
	,Heightfield = p2.Heightfield
	,Line = p2.Line
	,Plane = p2.Plane
	,Material = p2.Material
	,vec2=p2.vec2
	;
var PLAYER = Math.pow(2,0),
    ENEMY =  Math.pow(2,1),
    GROUND = Math.pow(2,2)

var p2Colors=['#845EC2','#D65DB1','#FF6F91','#FF9671','#CD6155','#C0392B','#A93226','#922B21','#B03A2E','#CB4335','#E74C3C','#EC7063','#AF7AC5','#9B59B6','#884EA0','#76448A','#0081CF','#2C73D2','#008E9B']

/**
//过滤碰撞形状
把形状分组
player1Shape.collisionGroup = PLAYER;
player2Shape.collisionGroup = PLAYER;
enemyShape  .collisionGroup = ENEMY;
groundShape .collisionGroup = GROUND;
分配每个形状碰撞的组。注意，玩家可以与地面和敌人相撞，但不能与其他玩家相撞。
player1Shape.collisionMask = ENEMY | GROUND;
player2Shape.collisionMask = ENEMY | GROUND;
enemyShape  .collisionMask = PLAYER | GROUND;
groundShape .collisionMask = PLAYER | ENEMY;
刚体类型,静态，动态，运动的，mass质量大于0默认动态,为0时默认静态
Body.STATIC,Body.DYNAMIC,Body.KINEMATIC,  刚体有三种类型
 */
function createWorld(x=0,y=9.8){
	var world = new World({gravity : [x,y]});
	return world;
}
function updateWorld(world,fps=1/10){
	world.step(fps);
	var len = world.bodies.length;
	for (var i = 0; i < len; i++) {
		var body = world.bodies[i];
		var display= body.display;
		if (display) {
			//将刚体的坐标和角度赋值给显示对象
			display.x = body.position[0];
			display.y = body.position[1];
			display.rotation = body.angle * 180 / Math.PI;
			//如果刚体当前状态为睡眠状态，将图片alpha设为0.5，否则为1
			if(body.sleepState == Body.SLEEPING){
				display.alpha = 0.5;
			}else{
				display.alpha = 1;
			}
		}
	}
}
function createWall(parent,width,height){
	let whs=[[width,10],[10,height],[width,10],[10,height]]
	let pos=[[width/2,0],[width,height/2],[width/2,height],[0,height/2]]
	for(var i=0;i<4;i++){
		let [wh,ps]=[whs[i],pos[i]];
		let box=createBox(ps[0],ps[1],wh[0],wh[1],0);
		parent.addChild(box);
	}
}
function createBox(x=0,y=0,w=50,h=50,mass=1,c=null){
	if(!c)c=p2Colors[Math.floor(Math.random()*p2Colors.length)];
	var display=new MSprite();
	display.dr(w,h,c).setCenter();
	var p2Shape= new Box({ width: w,height:h});//传入矩形宽高
	var body= new Body({ mass:mass,position:[x,y]});//传入刚体质量和坐标
	body.display=display;
	body.addShape(p2Shape);
	world.addBody(body);
	display.body=body;
	display.p2Shape=p2Shape;
	return display
}
function createCircle(x=0,y=0,r=25,mass=1,c=null){
	if(!c)c=p2Colors[Math.floor(Math.random()*p2Colors.length)];
	var display=new MSprite();
	display.dc(r,c);
	display.addChild(new MSprite().dc(2,'white').setPos(0,r-5))
	var p2Shape= new Circle({radius:r});//传入矩形宽高
	var body= new Body({ mass:mass,position:[x,y]});//传入刚体质量和坐标
	body.display=display;
	body.addShape(p2Shape);
	world.addBody(body);
	display.body=body;
	display.p2Shape=p2Shape;
	return display
}
